package com.ysld.backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysld.backend.entity.Order;
import com.ysld.backend.entity.Product;
import com.ysld.backend.util.CommonUtil;
import com.ysld.backend.util.OrderNoUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class OrderController {

    private static List<Product> PRODUCTS = new ArrayList<>();

    private static Map<String, Order> ORDER_DB = new HashMap<>();

    static {
        Product p1 = new Product(65069, "白金级保湿洁面乳", 189.69, 999);
        Product p2 = new Product(65061, "小棕瓶洁面啫喱霜", 110.23, 888);
        Product p3 = new Product(65062, "至尊光音典藏香水", 230.99, 777);
        PRODUCTS.add(p1);
        PRODUCTS.add(p2);
        PRODUCTS.add(p3);
    }

    /**
     * 获取商品列表
     * @return
     */
    @GetMapping("/products")
    public JSONObject getProducts(){
        return CommonUtil.successJson(PRODUCTS);
    }


    @PostMapping("/orders")
    public synchronized JSONObject order(@RequestBody OrderDto dto){
        Integer quantity = dto.getQuantity();
        Integer productId = dto.getProductId();

        if (quantity == null || quantity <= 0) {
            return CommonUtil.validErrorJson("quantity参数不合法");
        }

        List<Product> curProducts = PRODUCTS.stream().filter(p -> p.getId() == productId).collect(Collectors.toList());
        if (curProducts.isEmpty()) {
            return CommonUtil.notFoundJson("商品不存在");
        }

        Product product = curProducts.get(0);
        if (product.getStock() < quantity) {
            return CommonUtil.validErrorJson("抱歉，库存不足");
        }

        // 生成订单
        String orderId = OrderNoUtils.getNo();
        double price = product.getPrice() * quantity;
        Order order = new Order(orderId, productId, price);

        // 扣减库存
        product.setStock(product.getStock() - 1);

        // 订单入库
        ORDER_DB.put(orderId, order);

        return CommonUtil.successJson(order);
    }

    /**
     * 查询订单
     * @param id
     * @return
     */
    @GetMapping("/orders/{id}")
    public JSONObject order(@PathVariable("id") String id){

        return CommonUtil.successJson(ORDER_DB.get(id));
    }

}

class OrderDto {
    private Integer productId;
    private Integer quantity;

    public OrderDto(Integer productId, Integer quantity) {
        this.productId = productId;
        this.quantity = quantity;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
}
